import SparkMD5 from 'spark-md5'

let debounceTimer = null // 防抖动计时器
let throttleTimer = null // 节流计时器

/**
 * 防抖函数:
 *      防止抖动，单位时间内事件触发会被重置，避免事件被误伤触发多次。
 *      代码实现重在清零 clearTimeout
 */
export function debounce (f, wait = 100) {
    clearTimeout(debounceTimer) // 防抖重在清零
    debounceTimer = setTimeout(f, wait)
}

/**
 * 节流函数:
 *      节流：控制流量，单位时间内事件只能触发一次，如果服务器端的限流即 Rate Limit。
 *      代码实现重在开锁关锁 timer=timeout; timer=null
 */
export function throttle (f, wait = 100) {
    if (throttleTimer) {
        return
    }
    throttleTimer = setTimeout(() => {
        f()
        throttleTimer = null // 节流重在开关锁
    }, wait)
}

// 获取文件的md5值
export function getFileMd5 (file, callback) {
    const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice

    const chunkSize = 10 * 1024 * 1024
    // Read in chunks of 2MB

    const chunks = Math.ceil(file.size / chunkSize)

    let currentChunk = 0

    const spark = new SparkMD5.ArrayBuffer()

    const fileReader = new FileReader()

    fileReader.onload = function (e) {
        spark.append(e.target.result) // Append array buffer
        currentChunk++

        if (currentChunk < chunks) {
            loadNext()
        } else {
            callback && callback(spark.end())
        }
    }

    fileReader.onerror = function () {
        console.warn('oops, something went wrong.')
    }

    function loadNext () {
        var start = currentChunk * chunkSize

        var end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize

        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
    }

    loadNext()
}

// 延迟方法
export function delay (time = 50) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve()
        }, time)
    })
}


/*
 * 自定义文件下载
 *   url: 下载路径
 *   filename: 自定义名称
 **/
export function downloadFile (url, filename) {
    ajax(url, {
        responseType: 'blob'
    }).then(xhr => {
        let a = document.createElement('a')
        let blob = new window.Blob([xhr.response])
        // for IE
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveOrOpenBlob(blob, filename);
        } else {
            let url = window.URL.createObjectURL(blob)
            a.href = url
            a.download = filename
            a.click()
            window.URL.revokeObjectURL(url)
        }
    }).catch(err => {
        console.log(err)
    })
}

// get请求
function ajax (url, options) {
    return new Promise((resolve, reject) => {
        window.URL = window.URL || window.webkitURL
        let xhr = null
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xhr = new window.XMLHttpRequest()
        } else { // code for IE6, IE5
            xhr = new window.ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.open('get', url, true)
        if (options.responseType) {
            xhr.responseType = options.responseType
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(xhr)
                } else {
                    reject(xhr)
                }
            }
        }
        xhr.send()
    })
}

/*
 * 处理链接中的search拼接参数
 **/
export function getQuery (search) {
    let result = {}
    let link = search.replace(/\?/g, '')
    const tempArr = link.split('&')
    tempArr.forEach(str => {
        let arr = str.split('=')
        if (arr.length === 2) {
            result[arr[0]] = arr[1]
        }
    });
    return result
}